<template>
  <div ref="chartRef" :style="{ width, height }"></div>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted, onBeforeUnmount, markRaw } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '100%'
  },
  legend: {
    type: Object,
    default: null
  },
  title: {
    type: Object,
    default: null
  },
  graphic: {
    type: Object,
    default: null
  },
  toolbox: {
    type: Object,
    default: null
  },
  tooltip: {
    type: Object,
    default: null
  },
  grid: {
    type: Object,
    default: null
  },
  series: {
    type: Array,
    default: null
  },
  xAxis: {
    type: Array,
    default: null
  },
  yAxis: {
    type: Array,
    default: null
  },
  dataZoom: {
    type: Array,
    default: null
  },
  color: {
    type: Array,
    default: null
  }
});

const chartRef = ref(null);
const chart = ref(null);

const initChart = () => {
  console.log('执行了', props.legend);
  chart.value = markRaw(echarts.init(chartRef.value));
  chart.value.clear();
  const option = {
    color: props.color,
    title: props.title,
    legend: props.legend,
    tooltip: props.tooltip,
    graphic: props.graphic,
    grid: props.grid,
    xAxis: props.xAxis,
    yAxis: props.yAxis,
    series: props.series,
    dataZoom: props.dataZoom
  };
  console.log(option);
  chart.value.setOption(option);
};

const updateChart = () => {
  if (chartRef.value) {
    chart.value = markRaw(echarts.getInstanceByDom(chartRef.value));
    if (chart.value) {
      const option = {
        color: props.color,
        title: props.title,
        legend: props.legend,
        tooltip: props.tooltip,
        graphic: props.graphic,
        grid: props.grid,
        xAxis: props.xAxis,
        yAxis: props.yAxis,
        series: props.series,
        dataZoom: props.dataZoom
      };
      chart.value.setOption(option, true);
    }
  }
};

// Watch for changes in props
watch(() => props.xAxis, updateChart, { deep: true });
watch(
  () => props.series,
  (newVal) => {
    console.log('series变化了', newVal);
    initChart();
  },
  { deep: true }
);

// Lifecycle hooks
onMounted(initChart);
onBeforeUnmount(() => {
  if (chart.value) {
    chart.value.dispose();
  }
});
</script>

<style></style>
